<template>
  <div class="h-full w-full bg-black text-white overflow-hidden relative touch-none">
    <!-- 背景效果 -->
    <VocabularyBackground />

    <!-- 主要内容区域 -->
    <div class="flex flex-col relative z-10 h-full">
      <div class="flex-1 flex flex-col px-6 pt-6 mx-auto w-full h-full max-h-screen relative">
        <!-- 进度条和返回按钮 -->
        <ProgressHeader 
          :progress="wordData.progress" 
          :progress-text="ui.progressText" 
          @back="navigation.handleBack" 
        />

        <!-- 滚动内容区域 -->
        <div class="flex-1 overflow-y-auto custom-scrollbar w-full m-auto pb-28">
          <div class="flex-1 flex flex-col justify-between gap-8 will-change-transform pb-4 max-w-[800px] m-auto">
            <!-- 单词展示区域 -->
            <WordDisplay 
              v-if="wordData.currentWord" 
              :word="wordData.currentWord" 
              :show-definition="ui.showDefinition"
              @play-pronunciation="speech.playPronunciation" 
            />
            <div v-else class="text-center">
              <h2 class="text-2xl text-white/70">恭喜！你已完成所有单词学习</h2>
              <p class="mt-4 text-white/50">正在跳转到文章页面...</p>
            </div>

            <div v-if="wordData.currentWord" class="flex-1 flex flex-col">
              <!-- 例句区域 -->
              <ExampleSection 
                v-if="wordData.currentWord?.example?.text"
                :example="wordData.currentWord.example"
                :highlighted-example="wordData.highlightedExample"
                :show-definition="ui.showDefinition"
                @play-example="speech.playExampleSentence" 
              />

              <!-- 相关单词区域 -->
              <RelatedWordsSection 
                v-if="ui.showDefinition && hasRelatedWords" 
                :related-words="displayedRelatedWords"
                :show-all="ui.showAllRelatedWords"
                :has-more="hasMoreRelatedWords"
                :word-family="wordData.currentWord.wordFamily"
                :total-related-count="wordData.currentWord.relatedWords.length"
                @toggle-show-all="ui.showAllRelatedWords = !ui.showAllRelatedWords"
                @play-related-word="speech.playRelatedWord" 
              />

              <!-- 空内容提示 -->
              <div 
                v-if="ui.showDefinition && !hasExampleOrRelatedWords" 
                class="bg-white/5 rounded-[20px] p-6 text-center text-white/50"
              >
                暂无更多补充内容
              </div>
            </div>
          </div>
        </div>

        <!-- 底部按钮区域 -->
        <div class="absolute bottom-0 left-0 right-0 flex justify-center py-6 px-6 z-20 w-full">
          <div class="w-full max-w-[800px] m-auto">
            <ActionButtons 
              :current-word="wordData.currentWord"
              :show-definition="ui.showDefinition"
              :progress="wordData.progress"
              @response="wordLearning.handleResponse"
              @next-word="wordLearning.handleNextWord"
              @wrong="wordLearning.handleWrong"
              @generate-essay="navigation.generateEssay"
              @back="navigation.handleBack"
            />
          </div>
        </div>
      </div>
    </div>
  </div>  
</template>

<script setup>
import { ref, computed, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useModalStore } from '@/stores/modal';

// 导入子组件
import VocabularyBackground from './components/VocabularyBackground.vue';
import ProgressHeader from './components/ProgressHeader.vue';
import WordDisplay from './components/WordDisplay.vue';
import ExampleSection from './components/ExampleSection.vue';
import RelatedWordsSection from './components/RelatedWordsSection.vue';
import ActionButtons from './components/ActionButtons.vue';

// 从单独的文件导入辅助函数和模块
import { useSpeechModule } from './composables/useSpeech';
import { useWordLearning } from './composables/useWordLearning';
import { useNavigation } from './composables/navigationModule';

// ==================== 常量定义 ====================
const WORD_STATUS = {
  UNLEARNED: 0,
  KNOWN: 1,
  FUZZY: 2,
  UNKNOWN: 3
};

// ==================== 状态管理 ====================
const router = useRouter();
const route = useRoute();
const lessonId = computed(() => route.params.id || '未知课程');
const modalStore = useModalStore();

const wordData = reactive({
  knownQueue: [],
  learningQueue: [],
  currentWord: null,
  
  learningState: {
    totalWords: 0,
    learnedWords: 0,
    currentWordIndex: 0,
    totalVocabularyProgress: {
      totalLearnedWords: 0,
      totalWords: 0
    }
  },
  
  get highlightedExample() {
    const { example } = this.currentWord ?? {};
    if (!example?.text || !example?.highlight) return '';
    
    try {
      // 不区分大小写的替换
      const regex = new RegExp(example.highlight, 'i');
      return example.text.replace(
        regex, 
        match => `<span class='text-[#4A99E9] font-semibold'>${match}</span>`
      );
    } catch {
      return example.text;
    }
  },

  get progress() {
    const total = this.knownQueue.length + this.learningQueue.length;
    return total ? (this.knownQueue.length / total * 100) : 0;
  }
});

const ui = reactive({
  showDefinition: false,
  showAllRelatedWords: false,
  progressText: computed(() => `${Math.round(wordData.progress)}%`),
});

// ==================== 计算属性 ====================
const hasRelatedWords = computed(() => wordData.currentWord?.relatedWords?.length > 0);
const hasExampleOrRelatedWords = computed(() => 
  Boolean(wordData.currentWord?.example?.text || hasRelatedWords.value)
);
const hasMoreRelatedWords = computed(() => 
  wordData.currentWord?.relatedWords?.length > 3
);
const displayedRelatedWords = computed(() => {
  if (!wordData.currentWord?.relatedWords) return [];
  return ui.showAllRelatedWords 
    ? wordData.currentWord.relatedWords 
    : wordData.currentWord.relatedWords.slice(0, 3);
});

// ==================== 工具函数 ====================

// 添加会话学习记录
const sessionProgress = reactive({
  learned: 0,
  needsSaving: false
});

// 初始化各个功能模块
const speech = useSpeechModule(wordData);
const navigation = useNavigation(route, router, sessionProgress, wordData);
const wordLearning = useWordLearning(
  route.params.id, 
  wordData, 
  ui, 
  speech, 
  WORD_STATUS,
  sessionProgress
);

// ==================== 生命周期钩子 ====================
onMounted(() => {
  if ('speechSynthesis' in window) {
    window.speechSynthesis.getVoices();
  }
  
  // 保存当前课程 ID 到 modalStore
  if (route.params.id) {
    modalStore.setLastCourse(route.params.id);
  }
  
  wordLearning.loadWordData();
});

onBeforeUnmount(() => {
  if ('speechSynthesis' in window) {
    window.speechSynthesis.cancel();
  }
});
</script>

<style scoped>
* {
  touch-action: pan-y;
}

/* 自定义滚动条样式 */
.custom-scrollbar {
  scrollbar-width: thin;
  scrollbar-color: rgba(255, 255, 255, 0.2) transparent;
  -webkit-overflow-scrolling: touch; /* 增加iOS滚动支持 */
  overscroll-behavior: contain; /* 防止滚动穿透 */
}

.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: transparent;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background-color: rgba(255, 255, 255, 0.2);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 确保内容区域不被底部按钮遮挡 */
.pb-28 {
  padding-bottom: 7rem !important;
}

/* 高亮例句中的单词 */
:deep(span.text-\[#4A99E9\]) {
  color: #4A99E9;
  font-weight: bold;
}
</style> 